<template>
  <div
    :class="[
      'header-banner',
      'theme-QDS-light',
      { 'header-fixed': isMobile && showReset },
      { 'header-banner-bg': !isWeclome },
      { 'header-banner-bg-mobile': isMobile },
      { 'is-experience': isExperience },
      { 'bg-tr': isVoice },
    ]"
  >
    <div class="banner-wrap">
      <div class="banner-wrap__left">
        <v-button
          v-if="isExperience"
          type="link"
          class="back-btn"
          size="large"
          icon="arrow_left_small_line"
          remote
          @click="handleGoBack"
        ></v-button>
        <div class="left-logo">
          <img
            class="robot-avatar"
            v-if="!!(robotAvatar || transferAvatar)"
            :src="transferStatus ? transferAvatar : robotAvatar"
          />
        </div>
        <div class="left-title">
          <div :class="`main-title ${isExperience ? 'exp-main-title' : ''}`">
            {{ robotName }}
          </div>
          <div class="sub-title">
            {{ transferStatus ? "人工客服为您服务" : "" }}
          </div>
        </div>
      </div>
      <div v-if="webIMSource !== 'manage'">
        <div v-if="transferStatus" class="banner-wrap__right">
          <v-button type="text" class="reset-chat" @click="closeChatSession">
            <v-icon name="basic_exit_line" remote />
            结束会话
          </v-button>
        </div>
        <div v-else class="banner-wrap__right">
          <v-popmenu
            ref="resetBtn"
            placement="bottom-end"
            :options="getOptions()"
            v-model="firstVisible"
            @select="handleSelect"
          ></v-popmenu>
          <v-button
            v-if="showCall"
            type="text"
            @click="startCall"
          >
            <v-icon name="basic_call_line" remote />
          </v-button>
          <v-button
            v-if="showExperienceReset && getOptions().length > 0"
            :disabled="getOptions().length === 0"
            type="text"
            class="reset-chat"
            v-popmenu:resetBtn.click
          >
            <v-icon name="basic_brush_line" remote />
            <v-icon
              v-if="firstVisible"
              size="12"
              name="arrow_up_small_line"
              remote
            />
            <v-icon v-else size="12" name="arrow_down_small_line" remote />
          </v-button>
          <v-dialog
            v-model="resetConfirmDialog"
            :title="'确定要清空历史对话记录吗？'"
            kind="confirm"
            status="warning"
            @confirm="confirmReset"
          >
            <span slot="confirm-text">清空</span>
            <div>将清空当前会话的所有记录，并清空上下文关联</div>
          </v-dialog>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getQueryVariable } from "@/utils";
import { LLM_PLATFORM_MOBILE, LLM_PLATFORM_PC } from "@/constants";
export default {
  name: "CommonHeader",
  components: {},
  props: {
    isWeclome: {
      type: Boolean,
      default: false,
    },
    showReset: {
      type: Boolean,
      default: true,
    },
    isVoice: {
      type: Boolean,
      default: false,
    },
    from: {
      type: String, // manage - 管理后台   workbench - 坐席端
      default: "",
    },
    transferStatus: {
      type: Boolean,
      default: false,
    },
    transferAvatar: {
      type: String,
      default: "",
    },
    autoPlay: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    const isExperience = getQueryVariable("experience");
    const showExperienceReset = !getQueryVariable("hideReset");
    const showExperienceCreate = !getQueryVariable("hideCreate");
    return {
      asyncListCount: 0,
      autoplayVisible: false,
      showCall: false,
      showAutoplay: false,
      currentAutoPlay: this.autoPlay,
      LLM_PLATFORM_MOBILE,
      LLM_PLATFORM_PC,
      isResetDisable: true,
      robotName: "",
      robotAvatar: "",
      asyncVisible: false,
      firstVisible: false,
      options: [
        // { text: "清除上下文关联", value: "breakRelation" },
        { text: "清空历史对话记录", value: "resetSession" },
      ],
      options_exp: [{ text: "退出登录", value: "logout" }],
      async_opts: [
        { text: "同步调试", value: 0 },
        { text: "异步调试", value: 1 },
      ],
      webimToken: {},
      resetConfirmDialog: false,
      isExperience,
      showExperienceReset,
      showExperienceCreate,
      disableReset: false, // 重置对话按钮disable
    };
  },
  created() {
    const cachedConfig = this.$clientData.getConfigInfo();
    this.webimToken = window.webimToken[0] || {};
    this.debug_mode = this.webimToken.debug_mode;
    if (cachedConfig) {
      this.showCall = cachedConfig.ai_call.enable_voice_call;
      this.robotName = cachedConfig.name;
      this.robotAvatar = cachedConfig.avatar;
      if (cachedConfig.ai_call && cachedConfig.ai_call.enable_voice_call) {
        this.showCall =
          cachedConfig.ai_call.enable_voice_call &&
          cachedConfig.ai_call.enable_voice_interact;
      }
      if (cachedConfig && cachedConfig.ai_call) {
        this.showAutoplay = cachedConfig.ai_call.enable_voice_interact;
      }
    }

    // 监听配置信息，获取机器人名称
    this.$eventHub.$on("async_count_change", (res) => {
      this.asyncListCount = res.value;
    });

    // 监听配置信息，获取机器人名称
    this.$eventHub.$on("client_configChange", (res) => {
      this.robotName = res.name;
      this.robotAvatar = res.avatar;
      if (res.ai_call && res.ai_call.enable_voice_call) {
        this.showCall =
          res.ai_call.enable_voice_call && res.ai_call.enable_voice_interact;
      }
      res.ai_call && (this.showAutoplay = res.ai_call.enable_voice_interact);
    });

    this.$eventHub.$on("client_msgContentChange", (res) => {
      const { chatsContent } = res;
      // this.isResetDisable = chatsContent.length <= 0;
      this.isResetDisable =
        chatsContent.filter((item) => {
          return item.type !== 6;
        }).length <= 0;
    });
    this.$eventHub.$on("app_config_change", (res) => {
      this.robotName = res.appName;
      this.robotAvatar = res.appAvatar;
      if (res.ai_call && res.ai_call.enable_voice_call) {
        this.showCall =
          res.ai_call.enable_voice_call && res.ai_call.enable_voice_interact;
      }
    });
    this.$eventHub.$on("ai_config_change", (res) => {
      if (res.aiconfig) {
        this.showCall =
          res.aiconfig.enable_voice_call && res.aiconfig.enable_voice_interact;
      }
    });
  },
  watch: {
    autoPlay: function (val) {
      this.currentAutoPlay = val;
    },
  },
  async mounted() {
    this.$nextTick(() => {
      const cachedConfig = this.$clientData.getConfigInfo();
    });
  },
  methods: {
    async handleAutoPlayChange(val) {
      if (this.autoplayVisible) {
        this.$emit("autoPlayChange", val);
        setTimeout(() => {
          this.$refs.autoplayPop.hide();
        }, 500);
        if (this.webIMSource === "client") {
          await this.$clientData.modifyUserDialogConfig({
            auto_play: val ? "enable" : "disable",
          });
        }
        this.$emit("autoPlayChange", val);
      }
    },
    onAutoplaySelectPopChange(val) {
      this.autoplayVisible = val;
    },
    startCall() {
      this.$emit("startCall");
    },
    showApiSetModal() {
      const cachedConfig = this.$clientData.getConfigInfo();
      const payload = {
        from: "webim",
        type: "show_api_modal",
      };
      window.parent.postMessage(payload, "*");
    },
    showAsyncModal() {
      const cachedConfig = this.$clientData.getConfigInfo();
      const payload = {
        from: "webim",
        type: "show_async_modal",
      };
      window.parent.postMessage(payload, "*");
    },
    getOptions() {
      if (this.isResetDisable) {
        if (this.isMobile && this.isPhoneUser) {
          return this.options_exp;
        } else {
          return [];
        }
      } else {
        if (this.isMobile && this.isPhoneUser) {
          return [...this.options, ...this.options_exp];
        } else {
          return this.options;
        }
      }
    },
    isDeepSeekApp() {
      // deepseek官方app不展示图片 暂时这么处理
      let webimToken = window.webimToken[0];
      if (process.env.SERVER_ENV === "prod") {
        return webimToken.bot_biz_id === "1887453086201675776";
      } else if (process.env.SERVER_ENV === "test") {
        return webimToken.bot_biz_id === "1887055767721213952";
      } else {
        return false;
      }
    },
    clickTitleTag() {
      if (this.isMobile) {
        window.open(LLM_PLATFORM_MOBILE);
      } else {
        window.open(LLM_PLATFORM_PC);
      }
    },
    confirmReset() {
      this.$eventHub.$emit("reading_audio", {
        reading: false,
      });
      this.resetChat();
    },
    handleSelect(value) {
      const actionType = value.option.value;
      if (actionType === "breakRelation") {
        // 清空关联
        this.$emit("reset", "IsOnlyEmptyTheDialog");
      } else if (actionType === "resetSession") {
        this.resetConfirmDialog = true;
      }
    },
    handleGoBack() {
      if (this.isExperience) {
        const payload = JSON.stringify({
          from: "webim",
          type: "experience",
          action: "back",
        });
        window.parent.postMessage(payload, "*");
      }
    },
    handleCreateApp() {
      if (this.isExperience) {
        const payload = JSON.stringify({
          from: "webim",
          type: "experience",
          action: "create-experienceApp",
        });
        window.parent.postMessage(payload, "*");
      }
    },
    closeChatSession() {
      this.$clientData.closeChatSession();
    },
    resetChat() {
      this.$clientData.stopGeneration();
      this.$emit("reset");
      this.disableReset = true;
      // 一秒后才能再按重置
      setTimeout(() => {
        this.disableReset = false;
      }, 1000);
    },
  },
};
</script>

<style lang="less">
.header-banner {
  .divider {
    width: 1px;
    height: 16px;
    background: var(--color-divider-normal);
  }
  width: 100%;
  &.bg-tr {
    background: transparent !important;
  }
  &.header-banner-bg {
    // background: var(--inverse-opacity-5);
    background: #fff;
    backdrop-filter: blur(calc(40px / 2)) !important;
  }
  &.header-banner-bg-mobile {
    background: rgba(255, 255, 255, 0.4);
  }
  &.header-fixed {
    position: fixed;
    width: 100%;
    z-index: 10;
  }
  &.is-experience {
    background: none;
    padding: 0 32px;
    .banner-wrap {
      padding: 12px 0;
    }
    .robot-avatar {
      margin-right: 0;
      width: 40px;
      height: 40px;
      border-radius: var(--radius-large);
      border: var(--border-thickness) solid var(--color-divider-normal);
    }
  }

  .banner-wrap {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    z-index: 1;
    position: relative;

    &__left {
      display: flex;
      flex-direction: row;
      align-items: center;
      //   gap: 12px;
      gap: 3px;

      .left-logo {
        width: 32px;
        height: 32px;
      }

      .back-btn {
        .v-icon {
          width: 20px;
          height: 20px;
          vertical-align: text-top;
        }
      }

      .left-title {
        display: flex;
        flex-direction: column;

        .main-title {
          color: var(--text---color-text-primary);
          font: var(--subtitle-medium);
        }
        .exp-main-title {
          margin-left: 10px;
        }
      }
    }

    &__right {
      display: flex;
      align-items: center;
      //   gap: var(--spacing-base);
      //   gap: 3px;
      .autoplay-trigger {
        cursor: pointer;
        border-radius: 3px;
        display: flex;
        padding: 8px;
        align-items: center;
        gap: 1px;
        &:hover {
          background: var(--color-fill-hover);
        }
      }
      .reset-chat {
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 3px;
        .v-icon {
          //   margin-right: 5px;
        }
        .v-button.is-text.v-button--medium {
          padding: 5px 10px;
        }
      }
    }
  }
}

.manage-header {
  display: flex;
  height: var(--navbar-height, 64px);
  padding: var(--spacing-loose) var(--spacing-quite-loose);
  align-items: center;
  align-self: stretch;
  box-sizing: border-box;

  .banner-wrap {
    padding: 0;
    width: 100%;
    .robot-avatar {
      margin-right: 0;
    }
  }
}
.title-tag-class {
  cursor: pointer;
}
.auto-play-pop {
  display: flex;
  padding: var(--spacing-base-loose) var(--spacing-base-loose)
    var(--spacing-base-loose) var(--spacing-base-loose);
  align-items: center;
  gap: 8px;
  border-radius: var(--radius-normal);
  font-size: 14px;
  background: #fff;
  box-shadow: var(--shadow-medium-light);
}
</style>